package com.shareware.common.timer

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.os.Message
import com.shareware.common.NUMBER_ONE

/**
 * desc: 正计时
 * email: mobiledeveloper@qq.com
 */
abstract class AbstractUpTimer @JvmOverloads constructor(
    var timeStamp: Long = 1000,
    var interval: Long = 1000,
) {

    //是否暂停
    var isPause: Boolean = true
        private set

    /**
     * 当前时间
     */
    var currentTime: Long = 0

    private val upTimeStart = NUMBER_ONE
    private var isStart: Boolean = false

    @SuppressLint("HandlerLeak")
    private val upTimeHandler = object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            synchronized(this@AbstractUpTimer) {
                if (isPause) {
                    return
                }
                if (msg.what == upTimeStart) {
                    currentTime += timeStamp
                    onTick(currentTime)
                    sendMessageDelayed(obtainMessage(upTimeStart), interval)
                }
            }
        }
    }

    /**
     * 暂停时间
     */
    @Synchronized
    fun pause() {
        isPause = true
        isStart = false
        upTimeHandler.removeMessages(upTimeStart)
    }

    /**
     * 时间开启
     */
    @Synchronized
    fun start() {
        if (isStart) {
            return
        }
        isStart = true
        isPause = false
        upTimeHandler.removeMessages(upTimeStart)
        upTimeHandler.sendMessage(upTimeHandler.obtainMessage(upTimeStart))
    }

    /**
     * 计时器进行时，每秒触发一次
     */
    abstract fun onTick(millisUntilFinished: Long)
}